import { createSlice } from '@reduxjs/toolkit';
import type { PayloadAction } from '@reduxjs/toolkit';

interface AuthState {
    username: string;
    password: string;
    role: string;
    accessToken: string;
    isAuthenticated: boolean;
}

const initialState: AuthState = {
    username: '',
    password: '',
    role: '',
    accessToken: '',
    isAuthenticated: false,
}

const authSlice = createSlice({
    name: 'auth',
    initialState,
    reducers: {
        loginSuccess: (state, action: PayloadAction<{
            username: string;
            password: string;
            role: string;
            accessToken: string;
        }>) => {
            state.username = action.payload.username;
            state.password = action.payload.password;
            state.role = action.payload.role;
            state.accessToken = action.payload.accessToken;
            state.isAuthenticated = true;
        },
        updateAccessToken: (state, action: PayloadAction<string>) => {
            state.accessToken = action.payload;
        },
        logout: (state) => {
            state.username = '';
            state.password = '';
            state.role = '';
            state.accessToken = '';
            state.isAuthenticated = false;
        }
    }
})

export const { loginSuccess, logout, updateAccessToken } = authSlice.actions;
export default authSlice.reducer;